//
//  OAuthViewController.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/7/30.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController ,UIWebViewDelegate{

    
    private lazy var webView = UIWebView()
    
    
    //加载视图
    override func loadView() {
        
        view = webView
        webView.delegate = self
        
        title = "皓晨微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    //关闭按钮触发方法
    func close() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

    
        
        webView.loadRequest(NSURLRequest(URL:  NetWorkTools.sharedTools.oauth()))
    }

    
    //MARK 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
       
        SVProgressHUD.show()
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
  
        SVProgressHUD.dismiss()
    }
    
    //获取授权码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString  = request.URL!.absoluteString
        
        if !urlString.hasPrefix(NetWorkTools.sharedTools.redirecturi) {
            
            return true
        }

        print(request.URL?.query)
        //MARK :强制解包。改过尝试
        if let query = request.URL?.query where query.hasPrefix("code=") {
            
           let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            print("获取授权码"+code)
            loadAccessToken(code)
            
        }else {
            close()
        }
        
        return false
    }
    
    //获取AccessToken
    private func loadAccessToken(code:String) {
        
        NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil || result == nil {
                
               self.netError()
              
                return
            }
            
             //加载数据模型，回调错误信息
             // 1. 用 token 获取的信息创建用户账户模型
             // 2. 异步加载用户信息
             // 3. 保存用户信息(模型中完成)
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                
                if error != nil {
                    
                    self.netError()
                    return
                }
                
               NSNotificationCenter.defaultCenter().postNotificationName(ZuoJRootViewControllerSwitchNotification, object: false)
               self.close()
                
             })
        }
    }
    
    private func netError() {
        SVProgressHUD.showInfoWithStatus("您的网络有问题")
        
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) {
            
            self.close()
        }
    }
}
